{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "from stable_baselines3 import PPO\n",
    "import gym\n",
    "import stable_baselines3 as sb3"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([0.03038724, 0.04384034, 0.01150149, 0.02461213], dtype=float32)"
      ]
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 定义环境\n",
    "class MyWrapper(gym.Wrapper):\n",
    "    def __init__(self):\n",
    "        env = gym.make('CartPole-v1')\n",
    "        super().__init__(env)\n",
    "        self.env = env\n",
    "\n",
    "    def reset(self):\n",
    "        state,_ = self.env.reset()\n",
    "        return state\n",
    "    def step(self,action):\n",
    "        state,reward,done,_,info = self.env.step(action)\n",
    "        return state,reward,done,info\n",
    "\n",
    "env = MyWrapper()\n",
    "env.reset()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Using cuda device\n",
      "Wrapping the env with a `Monitor` wrapper\n",
      "Wrapping the env in a DummyVecEnv.\n"
     ]
    },
    {
     "data": {
      "text/html": [
       "<pre style=\"white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace\">d:\\Anaconda install\\envs\\Gym\\lib\\site-packages\\rich\\live.py:231: UserWarning: install \"ipywidgets\" for Jupyter \n",
       "support\n",
       "  warnings.warn('install \"ipywidgets\" for Jupyter support')\n",
       "</pre>\n"
      ],
      "text/plain": [
       "d:\\Anaconda install\\envs\\Gym\\lib\\site-packages\\rich\\live.py:231: UserWarning: install \"ipywidgets\" for Jupyter \n",
       "support\n",
       "  warnings.warn('install \"ipywidgets\" for Jupyter support')\n"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "---------------------------------\n",
      "| rollout/           |          |\n",
      "|    ep_len_mean     | 120      |\n",
      "|    ep_rew_mean     | 120      |\n",
      "| time/              |          |\n",
      "|    fps             | 427      |\n",
      "|    iterations      | 1        |\n",
      "|    time_elapsed    | 4        |\n",
      "|    total_timesteps | 2048     |\n",
      "---------------------------------\n",
      "------------------------------------------\n",
      "| rollout/                |              |\n",
      "|    ep_len_mean          | 131          |\n",
      "|    ep_rew_mean          | 131          |\n",
      "| time/                   |              |\n",
      "|    fps                  | 345          |\n",
      "|    iterations           | 2            |\n",
      "|    time_elapsed         | 11           |\n",
      "|    total_timesteps      | 4096         |\n",
      "| train/                  |              |\n",
      "|    approx_kl            | 0.0075974455 |\n",
      "|    clip_fraction        | 0.0474       |\n",
      "|    clip_range           | 0.2          |\n",
      "|    entropy_loss         | -0.592       |\n",
      "|    explained_variance   | 0.267        |\n",
      "|    learning_rate        | 0.0003       |\n",
      "|    loss                 | 14.9         |\n",
      "|    n_updates            | 10           |\n",
      "|    policy_gradient_loss | -0.00867     |\n",
      "|    value_loss           | 68.3         |\n",
      "------------------------------------------\n",
      "-----------------------------------------\n",
      "| rollout/                |             |\n",
      "|    ep_len_mean          | 132         |\n",
      "|    ep_rew_mean          | 132         |\n",
      "| time/                   |             |\n",
      "|    fps                  | 298         |\n",
      "|    iterations           | 3           |\n",
      "|    time_elapsed         | 20          |\n",
      "|    total_timesteps      | 6144        |\n",
      "| train/                  |             |\n",
      "|    approx_kl            | 0.007942231 |\n",
      "|    clip_fraction        | 0.0421      |\n",
      "|    clip_range           | 0.2         |\n",
      "|    entropy_loss         | -0.585      |\n",
      "|    explained_variance   | 0.664       |\n",
      "|    learning_rate        | 0.0003      |\n",
      "|    loss                 | 15.7        |\n",
      "|    n_updates            | 20          |\n",
      "|    policy_gradient_loss | -0.00524    |\n",
      "|    value_loss           | 43.3        |\n",
      "-----------------------------------------\n",
      "------------------------------------------\n",
      "| rollout/                |              |\n",
      "|    ep_len_mean          | 148          |\n",
      "|    ep_rew_mean          | 148          |\n",
      "| time/                   |              |\n",
      "|    fps                  | 280          |\n",
      "|    iterations           | 4            |\n",
      "|    time_elapsed         | 29           |\n",
      "|    total_timesteps      | 8192         |\n",
      "| train/                  |              |\n",
      "|    approx_kl            | 0.0059157326 |\n",
      "|    clip_fraction        | 0.0499       |\n",
      "|    clip_range           | 0.2          |\n",
      "|    entropy_loss         | -0.579       |\n",
      "|    explained_variance   | 0.559        |\n",
      "|    learning_rate        | 0.0003       |\n",
      "|    loss                 | 17.3         |\n",
      "|    n_updates            | 30           |\n",
      "|    policy_gradient_loss | -0.00956     |\n",
      "|    value_loss           | 56.3         |\n",
      "------------------------------------------\n"
     ]
    },
    {
     "data": {
      "text/html": [
       "<pre style=\"white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace\"></pre>\n"
      ],
      "text/plain": []
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "text/html": [
       "<pre style=\"white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace\">\n",
       "</pre>\n"
      ],
      "text/plain": [
       "\n"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "text/plain": [
       "<stable_baselines3.ppo.ppo.PPO at 0x19e5a1954f0>"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "#创建模型\n",
    "model = PPO('MlpPolicy',env,verbose=1) #verbos： 是否打印日志\n",
    "\n",
    "#加载参数\n",
    "model.set_parameters('/model_weights/PPO_model.zip')\n",
    "\n",
    "#继续训练\n",
    "model.learn(8000,progress_bar=True)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "d:\\Anaconda install\\envs\\Gym\\lib\\site-packages\\stable_baselines3\\common\\evaluation.py:67: UserWarning: Evaluation environment is not wrapped with a ``Monitor`` wrapper. This may result in reporting modified episode lengths and rewards, if other wrappers happen to modify these. Consider wrapping environment first with ``Monitor`` wrapper.\n",
      "  warnings.warn(\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "(876.7, 380.2025907328881)"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from stable_baselines3.common.evaluation import evaluate_policy #测试函数\n",
    "\n",
    "evaluate_policy(model,env,n_eval_episodes=10)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Gym",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.16"
  },
  "orig_nbformat": 4
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
